<?php
/**
 * Leek - Zend Framework Components
 *
 * @category   Leek
 * @package    Leek_MultiDb
 * @author     Chris Jones <leeked@gmail.com>
 * @link       http://code.google.com/p/leek-zf-components/
 * @license    http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @version    $Id: MultiDb.php 53 2009-06-04 15:24:26Z leeked $
 */

/**
 * Handles retrieving multiple database instances
 *
 * @category   Leek
 * @package    Leek_MultiDb
 * @author     Chris Jones <leeked@gmail.com>
 * @link       http://code.google.com/p/leek-zf-components/
 * @license    http://www.opensource.org/licenses/bsd-license.php New BSD License
 */
class Leek_MultiDb
{
    /**
     * @var Zend_Controller_Front
     */
    protected $_front;

    /**
     * @var array
     */
    protected $_multiDb;

    /**
     * Retreive a master instance of the Db
     *
     * @param string $dbName
     * @return Zend_Db_Adapter
     */
    public function getMaster($dbName, $multiDb = null)
    {
        $dbName .= '_master';
        return $this->getSlave($dbName, null, $multiDb);
    }

    /**
     * Retreive a slave instance of the Db
     *
     * @param string $dbName
     * @param int    $mod
     * @return Zend_Db_Adapter
     */
    public function getSlave($dbName, $mod = null, $multiDb = null)
    {
        if ($multiDb == null) {
            $multiDb = $this->getMultiDb();
        }

        if (isset($multiDb[$dbName])) {

            $slaveCount = count($multiDb[$dbName]);

            if ($mod === null) {

                $index = rand(0, ($slaveCount - 1));
                return $multiDb[$dbName][$index];

            } else {

                $mod = (int) $mod;
                return $multiDb[$dbName][$mod % $slaveCount];

            }

        }

        return false;
    }

    /**
     * Retrieve multidb resource instance
     *
     * @return array
     */
    public function getMultiDb()
    {
        if (null === $this->_multiDb) {
            $this->_multiDb = $this->getFrontController()->getParam('bootstrap')->getResource('multidb');
        }
        return $this->_multiDb;
    }

    /**
     * Retrieve front controller instance
     *
     * @return Zend_Controller_Front
     */
    public function getFrontController()
    {
        if (null === $this->_front) {
            $this->_front = Zend_Controller_Front::getInstance();
        }
        return $this->_front;
    }
}
